import {
    fetchData
} from '../../utils/request'
var app = getApp();
const baseUrl = app.globalData.root;
import Dialog from '../../miniprogram_npm/vant-weapp/dialog/dialog';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        title: "登录",
        root: app.globalData.root,
        username: '',
        password: '',
        isShow: false,
        canIUseGetUserProfile: wx.canIUse('getUserProfile'),
         canIUseNicknameComp: wx.canIUse('input.type.nickname'),
        current: 1,
        registerData: {},
        show: true,
        userinfo: {},
        avatar: "http://39.107.110.103:9000/property-management/images/user.png",
        codeText: '获取验证码',
        counting: false,
        ispassword: true,
        usernameRule: [{
            type: 'number'
        }],
        passwordRule: [{
            type: 'number'
        }]
    },
    //-------------------------------路由跳转页面----------------------
    toForgetPage() {
        wx.navigateTo({
            url: '/pages/login/forget/forget',
        })
    },

    // 登陆注册监听
    click(e) {
        let index = e.currentTarget.dataset.code;
        // if(index==0){
        //     this.setData({
        //         isShowMsg: true,
        //         msg: '此功能暂未开放!!!',
        //         type: "warning"
        //       })  
        //       return
        // }
        this.setData({
            current: index
        })
    },
    wxLogin(){
        let that=this
        wx.login({
                    success(res) {
                        if (res.code) {
                            that.getOpenIdAndSessionKey(res.code)
                        
                        } else {
                            console.log('登录失败！' + res.errMsg)
                        }
                    }
                })
    },
    getOpenIdAndSessionKey(code){
        fetchData(`/wx/common/getOpenId?code=${code}`,"","GET",res=>{
           if(res.data.code==200){
            wx.setStorageSync('userInfo', res.data.data)
            this.wxLoginByOpenId(res.data.data.openid)
           }
        },err=>{
            console.log(err);
        })
    },
    wxLoginByOpenId(openid){
        let that=this;
        fetchData(`/mLoginByOpenid?openid=${openid}`,"","GET",res=>{
            if (res.data.code == 200) {
                wx.showToast({
                    icon: 'success',
                    title: "登录成功!!",
                    duration: 1500,
                    mask: true,
                })
                //将token存储
                wx.setStorageSync('token', res.data.token);

                //调用获取用户信息方法
                that.getUserInFo();

            } else {
                wx.showToast({
                    icon: 'none',
                    title: res.msg,
                    duration: 1500,
                    mask: true,
                })
            }
        })
    },
    uploadAvatar(url){
        let that=this;
        wx.uploadFile({
            url:baseUrl+'/common/uploadMinio', // 仅为示例，非真实的接口地址
            filePath: url,
            name: 'file',
            success(res) {
                wx.hideLoading();
               const data=JSON.parse(res.data);
             if(data.code==200){
                that.setData({
                  avatar:data.url
                })
                that.wxLogin()
             }
            },
            fail(err){
                console.log(err
                  );
            }
          });
    },
    onChooseAvatar(e) {
        const { avatarUrl } = e.detail 
        this.uploadAvatar(avatarUrl)
      },
    getUserProfile(e) {
        // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
        wx.getUserProfile({
          desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
          success: (res) => {
            console.log(res)
            this.setData({
              userInfo: res.userInfo,
              hasUserInfo: true
            })
          },
          fail:(err)=>{
              console.log(err);
          }
        })
      },
    bindWx() {
        Dialog.confirm({
                title: '微信授权',
                message: "Miku物业将会获取您的个人信息"
            })
            .then(() => {
                // on confirm
                // wx.showLoading()
                this.wxLogin()
                this.getUserProfile()
                // let that = this
                



            })
            .catch(() => {
                // on cancel
            });

    },
    //获取验证码 
    getCode() {
        var that = this;
        if (!this.data.registerData.email || !this.checkEmailRole(this.data.registerData.email)) {
            wx.showToast({
                title: '邮箱有误',
                icon: "error"
            })
            return;
        }
        if (!that.data.counting) {
            wx.showToast({
                title: '验证码已发送',
            })
            that.sendEmail(that.data.registerData.email)
            //开始倒计时60秒
            that.countDown(that, 60);
        }
    },
    //倒计时60秒
    countDown(that, count) {
        if (count == 0) {
            that.setData({
                codeText: '获取验证码',
                counting: false
            })
            return;
        }
        that.setData({
            counting: true,
            codeText: count + '秒后重新获取',
        })
        setTimeout(function () {
            count--;
            that.countDown(that, count);
        }, 1000);
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        if (wx.getStorageSync('token')) {
            wx.switchTab({
                url: '../../pages/warehouse/me/me',
            });
        }
    },
    changePasswordSee() {
        this.setData({
            ispassword: !this.data.ispassword
        })
    },
    // 获取输入账号 
    usernameInput: function (e) {
        this.setData({
            username: e.detail.value
        })
    },
    bindUsername(e) {
        this.setData({
            ["registerData.username"]: e.detail.value
        })
    },
    bindEmail(e) {
        this.setData({
            ["registerData.email"]: e.detail.value
        })
    },
    bindCode(e) {
        this.setData({
            ["registerData.code"]: e.detail.value
        })
    },
    bindPassword(e) {
        this.setData({
            ["registerData.password"]: e.detail.value
        })
    },
    bindRePassword(e) {
        this.setData({
            ["registerData.repassword"]: e.detail.value
        })
    },
    // 获取输入密码 
    passwordInput: function (e) {
        this.setData({
            password: e.detail.value
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 登录方法
     */
    Login: function () {
        if (this.data.current == 1) {
            if (this.data.username == '') {
                wx.showToast({
                    icon: 'none',
                    title: "账号不能为空",
                    duration: 1500,
                    mask: true,
                })
                return
            }
            if (this.data.password == '') {
                wx.showToast({
                    icon: 'none',
                    title: "密码不能为空",
                    duration: 1500,
                    mask: true,
                })
                return
            }
            var that = this;
            that.setData({
                isShowMsg: true,
                msg: '加载中',
                type: "loading"
            })
            let loginBody = {
                username: this.data.username,
                password: this.data.password,
            }
            fetchData("/mLogin", loginBody, "POST", res => {
                that.setData({
                    isShow: false
                })
                if (res.data.code == 200) {
                    wx.showToast({
                        icon: 'success',
                        title: "登录成功!!",
                        duration: 1500,
                        mask: true,
                    })
                    //将token存储
                    wx.setStorageSync('token', res.data.token);

                    //调用获取用户信息方法
                    that.getUserInFo();

                } else {
                    wx.showToast({
                        icon: 'none',
                        title: res.msg,
                        duration: 1500,
                        mask: true,
                    })
                }
            }, err => {
                wx.showToast({
                    icon: 'none',
                    title: err.data.msg,
                    duration: 1500,
                    mask: true,
                })
            })
        } else {
            //注册
            this.validateEmail(this.data.registerData.email, this.data.registerData.code);

        }
    },


    // 获取用户信息
    getUserInFo: function () {
        fetchData("/getInfo", {}, "GET", res => {
            if (res.data.code == 200) {
                //存储用户信息
                let user = res.data.user
                wx.setStorageSync('user', user)
                if (user != null) {
                    wx.switchTab({
                        url: '/pages/home/home',
                    })
                    //跳转页面
                    // wx.navigateTo({
                    //     url: '/pages/list/list',
                    // });
                } else {
                    //重新登录
                    wx.navigateTo({
                        url: '/pages/login/login',
                    });
                }

            }
        }, err => {

        })

    },
    checkEmailRole(email) {
        var reEml = /^[\w\-\.]+@[a-z0-9]+(\-[a-z0-9]+)?(\.[a-z0-9]+(\-[a-z0-9]+)?)*\.[a-z]{2,4}$/i;
        if (!reEml.test(email)) {
            wx.showToast({
                title: '邮箱不合规',
                icon: 'none'
            })
            return false;
        }
        return true;
    },
    validateEmail(email, code) {
        fetchData(`/captcha/validateEmailCode?email=${email}&content=${code}`, "", "GET", res => {
            if (res.data.code == 500) {
                wx.showToast({
                    title: '验证码错误！！',
                    icon: "error"
                })
                return;
            }
            fetchData("/register", this.data.registerData, "POST", res => {
                if (res.data.code == 200) {
                    wx.showToast({
                        title: '注册成功',
                    })
                    this.setData({
                        current: 1
                    })
                }
            })

        })
    },
    sendEmail(email) {
        fetchData(`/captcha/email-captcha?email=${email}`, "", 'GET', res => {
            console.log(res);
        })
    },


    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})